import { View, Text, Input } from '@tarojs/components'
import React, { useState, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import Taro from '@tarojs/taro'
import { updateLocation } from '../../store/slices/userSlice'
import { LOCATION_APIKEY } from '../../config'
import FoodCard from '../../components/FoodCard'
import './index.scss'

const Home = () => {
  const dispatch = useDispatch()
  const { name: locationName } = useSelector(state => state.user.location)
  const [searchValue, setSearchValue] = useState('')
  const [mapLoaded, setMapLoaded] = useState(false)

  useEffect(() => {
    // 初始化高德地图
    if (process.env.TARO_ENV === 'h5' && !mapLoaded) {
      const script = document.createElement('script')
      script.src = `https://webapi.amap.com/maps?v=2.0&key=${LOCATION_APIKEY}`
      script.async = true
      script.onload = () => {
        setMapLoaded(true)
      }
      script.onerror = () => {
        console.error('高德地图加载失败')
      }
      document.head.appendChild(script)
    }
  }, [mapLoaded])

  const categories = [
    { icon: 'fa-utensils', text: '中餐', color: 'red' },
    { icon: 'fa-hamburger', text: '西餐', color: 'blue' },
    { icon: 'fa-fish', text: '日料', color: 'green' },
    { icon: 'fa-pepper-hot', text: '川菜', color: 'yellow' },
    { icon: 'fa-ellipsis-h', text: '更多', color: 'purple' }
  ]

  const foods = [
    {
      id: '1',
      name: '香辣牛肉面',
      price: 28,
      time: '15分钟',
      type: '中式面食',
      image: 'https://images.unsplash.com/photo-1555126634-323283e090fa',
      rating: 4.5,
      ratingCount: 328,
      distance: '500m',
      tag: '午餐热门'
    },
    {
      id: '2',
      name: '意式肉酱披萨',
      price: 58,
      time: '25分钟',
      type: '意式料理',
      image: 'https://images.unsplash.com/photo-1513104890138-7c749659a591',
      rating: 4.8,
      ratingCount: 256,
      distance: '1.2km',
      tag: '同事最爱'
    }
  ]

  const handleSearch = (value) => {
    setSearchValue(value)
  }

  const handleLocation = () => {
    if (process.env.TARO_ENV === 'h5') {
      // H5 环境使用高德地图选点
      window.AMap.plugin('AMap.CitySearch', () => {
        const citySearch = new window.AMap.CitySearch()
        citySearch.getLocalCity((status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            window.AMap.plugin('AMap.Geolocation', () => {
              const geolocation = new window.AMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 10000,
                buttonPosition: 'RB',
                buttonOffset: new window.AMap.Pixel(10, 20),
                zoomToAccuracy: true
              })
              geolocation.getCurrentPosition((status, result) => {
                if (status === 'complete') {
                  dispatch(updateLocation({
                    name: result.formattedAddress,
                    latitude: result.position.lat,
                    longitude: result.position.lng
                  }))
                } else {
                  Taro.showToast({
                    title: '定位失败',
                    icon: 'none'
                  })
                }
              })
            })
          }
        })
      })
    } else {
      // 小程序环境使用原生接口
      Taro.chooseLocation({
        success: function (res) {
          dispatch(updateLocation({
            name: res.name,
            latitude: res.latitude,
            longitude: res.longitude
          }))
        }
      })
    }
  }

  const handleFoodClick = (id) => {
    Taro.navigateTo({
      url: `/pages/detail/index?id=${id}`
    })
  }

  const handleRandomClick = () => {
    Taro.navigateTo({
      url: '/pages/random/index'
    })
  }

  const handleFilterClick = () => {
    Taro.navigateTo({
      url: '/pages/filter/index'
    })
  }

  return (
    <View className='home'>
      {/* 搜索栏 */}
      <View className='search-bar'>
        <View className='search-input'>
          <Text className='fa-solid fa-magnifying-glass icon-search' />
          <Input
            type='text'
            placeholder='搜索美食、餐厅...'
            value={searchValue}
            onInput={e => handleSearch(e.detail.value)}
          />
        </View>
        <Text className='fa-solid fa-bell icon-bell' />
      </View>

      {/* 位置选择 */}
      <View className='location' onClick={handleLocation}>
        <View className='location__left'>
          <Text className='fa-solid fa-location-dot icon-map-marker' />
          <Text className='location__text'>{locationName}</Text>
          <Text className='fa-solid fa-chevron-down icon-chevron-down' />
        </View>
        <View className='location__right'>
          <Text className='fa-solid fa-clock icon-clock' />
          <Text className='location__time'>午餐时间</Text>
        </View>
      </View>

      {/* 决策按钮 */}
      <View className='decision'>
        <Text className='decision__title'>今天吃什么？</Text>
        <View className='decision__buttons'>
          <View className='decision__button decision__button--primary' onClick={handleRandomClick}>
            <Text className='fa-solid fa-dice icon' />
            <Text>随机推荐</Text>
          </View>
          <View className='decision__button decision__button--outline' onClick={handleFilterClick}>
            <Text className='fa-solid fa-filter icon' />
            <Text>智能筛选</Text>
          </View>
        </View>
      </View>

      {/* 分类导航 */}
      <View className='categories'>
        {categories.map((category, index) => (
          <View key={index} className='category'>
            <View className={`category__icon category__icon--${category.color}`}>
              <Text className={`fa-solid ${category.icon} icon`} />
            </View>
            <Text className='category__text'>{category.text}</Text>
          </View>
        ))}
      </View>

      {/* 附近推荐 */}
      <View className='nearby'>
        <View className='nearby__header'>
          <Text className='nearby__title'>附近推荐</Text>
          <View className='nearby__more'>
            <Text>查看更多</Text>
            <Text className='fa-solid fa-chevron-right icon' />
          </View>
        </View>
        <View className='nearby__list'>
          {foods.map(food => (
            <FoodCard
              key={food.id}
              food={food}
              onClick={() => handleFoodClick(food.id)}
            />
          ))}
        </View>
      </View>
    </View>
  )
}

export default Home 